package utils

import (
	"context"
	"errors"
	"fmt"
	"gitcode.com/G-YT/iHealth25/server/global"
	"gitcode.com/G-YT/iHealth25/server/model/hierarchy"
	"gitcode.com/G-YT/iHealth25/server/model/user"
	"strconv"
	"time"

	"gorm.io/gorm"
)

//@author: [songzhibin97](https://github.com/songzhibin97)
//@function: ClearTable
//@description: 清理数据库表数据
//@param: db(数据库对象) *gorm.DB, tableName(表名) string, compareField(比较字段) string, interval(间隔) string
//@return: error

func ClearTable(db *gorm.DB, tableName string, compareField string, interval string) error {
	if db == nil {
		return errors.New("db Cannot be empty")
	}
	duration, err := time.ParseDuration(interval)
	if err != nil {
		return err
	}
	if duration < 0 {
		return errors.New("parse duration < 0")
	}
	return db.Debug().Exec(fmt.Sprintf("DELETE FROM %s WHERE %s < ?", tableName, compareField), time.Now().Add(-duration)).Error
}

// CheckExpiredMembers 检测过期会员
func CheckExpiredMembers(db *gorm.DB) error {
	fmt.Println("Executing expire member check...")
	// 查询每个用户最近的一条开通记录
	var records []user.Vip
	if err := db.Model(&user.Vip{}).Order("id, updated_at DESC").Group("uid").Find(&records).Error; err != nil {
		fmt.Println("查询开通会员记录错误:", err)
		return err
	}
	// 遍历记录进行处理
	for _, v := range records {
		// 检查条件
		if v.Status == 2 && v.ExpiredAt.Before(time.Now()) {
			// 更新开通记录状态
			if err := db.Model(&user.Vip{}).Where("id = ?", v.ID).Update("status", 3).Error; err != nil {
				fmt.Printf("修改失败的用户ID为%d: %v\n", v.Uid, err)
				uidString := strconv.Itoa(int(v.Uid))
				return errors.New("修改失败的用户ID为:" + uidString)
			}
			// 更新用户类型
			if err := db.Model(&user.User{}).Where("id = ?", v.Uid).Update("types", 3).Error; err != nil {
				uidString := strconv.Itoa(int(v.Uid))
				return errors.New("修改失败的用户ID为:" + uidString)
			}
			fmt.Printf("更新类型的用户ID为%d\n", v.Uid)
		}
	}
	return nil
}

// UpdateCountData 更新统计数据
func UpdateCountData() error {
	fmt.Println("Updating count data...")
	//设置KEY
	key := "Count:redis"
	err := global.GVA_REDIS.Del(context.Background(), key).Err()
	var UsersTotal int64
	var audioArticlePvTotal int64
	var graphicArticlePvTotal int64
	var videoArticlePvTotal int64
	// 获取用户总数
	err = global.GVA_DB.Model(&user.User{}).Count(&UsersTotal).Error
	// 获取文章总浏览量
	err = global.GVA_DB.Model(&hierarchy.FdArticleAudio{}).Select("SUM(pv)").Scan(&audioArticlePvTotal).Error
	err = global.GVA_DB.Model(&hierarchy.FdArticleGraphic{}).Select("SUM(pv)").Scan(&graphicArticlePvTotal).Error
	err = global.GVA_DB.Model(&hierarchy.FdArticleVideo{}).Select("SUM(pv)").Scan(&videoArticlePvTotal).Error
	PvTotal := audioArticlePvTotal + graphicArticlePvTotal + videoArticlePvTotal
	var pvTotalStr string
	if PvTotal <= 50000 {
		pvTotalStr = "5万"
	} else if PvTotal < 100000000 || PvTotal > 50000 {
		pvTotalStr = fmt.Sprintf("%.2f万", float64(PvTotal)/10000)
	} else {
		pvTotalStr = "9999+万"
	}
	//usersTotal := fmt.Sprintf("%.2f", float64(UsersTotal)*0.1)
	usersTotal := fmt.Sprintf("%#v", float64(UsersTotal))

	hashData := map[string]interface{}{
		"users_total": usersTotal,
		"pv_total":    pvTotalStr,
	}
	err = global.GVA_REDIS.HMSet(context.Background(), key, hashData).Err()
	if err != nil {
		return err
	}
	return nil
}
